﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
using YunSteelyard.util;
using System.Text.RegularExpressions;

namespace YunSteelyard
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();

        }

        public Form2(UserInfo userInfo)
        {
            // TODO: Complete member initialization
            this.userInfo = userInfo;
            InitializeComponent();
        }

        private UserInfo userInfo; 

        private void Form2_Load(object sender, EventArgs e)
        {
            MysqlUtil db = new MysqlUtil();
            DataSet ds = db.GetDataSet("select * from position_info GROUP BY ID");
            DataTable dt = ds.Tables[0];
            comboBox3.Items.Clear();

            this.comboBox3.DataSource = dt;
            this.comboBox3.DisplayMember = "position";
            this.comboBox3.ValueMember = "ID";

            comboBox3.SelectedItem = null;

            string[] ports = SerialPort.GetPortNames();
            if (ports.Length == 0)
            {
                MessageBox.Show("没有检测到端口");
            }
            try
            {
                comboBox2.Items.Clear();
                foreach (string port in ports)
                {
                    comboBox2.Items.Add(port);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "提示信息");
            }

            //程序启动后每10秒向秤发送一次数据请求
            System.Timers.Timer t = new System.Timers.Timer(10000);
            t.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
            //每到指定时间Elapsed事件是触发一次（false），还是一直触发（true）
            t.AutoReset = true;
            //是否触发Elapsed事件
            t.Enabled = true;
            t.Start();

            if (File.Exists(@"D:\\ak.txt"))
            {
                StreamReader sr = new StreamReader("D:\\ak.txt", Encoding.UTF8);
                if (!sr.EndOfStream)
                {
                    String line = sr.ReadLine();
                    String[] lineArray = Regex.Split(line, "@@@@", RegexOptions.IgnoreCase);
                    if (line != null && lineArray.Length == 3)
                    {
                        String positionStrId = lineArray[0].Substring(lineArray[0].IndexOf(":") + 1);
                        String steelyardNameId = lineArray[1].Substring(lineArray[1].IndexOf(":") + 1);
                        String portsStr = lineArray[2].Substring(lineArray[2].IndexOf(":") + 1);
                        //comboBox3.ValueMember = positionStrId;
                        comboBox3.SelectedValue = positionStrId;
                        //comboBox1.ValueMember = steelyardNameId;
                        comboBox1.SelectedValue = steelyardNameId;
                        comboBox2.Text = portsStr;
                    }
                }
                sr.Close();
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            String postion = this.comboBox3.Text;
            String steelyardId = this.comboBox1.Text;
            String comNo = this.comboBox2.Text;

            //保存数据用
            //byte[] byData = new byte[100];
            //char[] charData = new char[1000];
            if (postion == "")
            {
                MessageBox.Show("指定设备位置", "提示信息");
                return;
            }
            if (steelyardId == "")
            {
                MessageBox.Show("指定一个设备号", "提示信息");
                return;
            }
            if (comNo == "")
            {
                MessageBox.Show("指定一个传输端口", "提示信息");
                return;
            }

            //将数据下载到本地文件中
            FileStream fs = new FileStream("D:\\ak.txt", FileMode.Create);
            //获得字节数组
            byte[] data = System.Text.Encoding.GetEncoding("utf-8").GetBytes("position:" + comboBox3.SelectedValue + "@@@@" + "steelyardName:" + comboBox1.SelectedValue + "@@@@" + "ports:" + comboBox2.Text);
            //开始写入
            fs.Write(data, 0, data.Length);
            //清空缓冲区、关闭流
            fs.Flush();
            fs.Close();

            //Control.CheckForIllegalCrossThreadCalls = false;
            ////到达指定时间5秒触发该事件
            //serialPort1.Close();
            //serialPort1.PortName = this.comboBox2.Text.ToString();
            //serialPort1.BaudRate = int.Parse("9600");
            //serialPort1.DataBits = int.Parse("8");
            //serialPort1.Parity = Parity.None;
            //serialPort1.StopBits = StopBits.One;

            //serialPort1.Open();
            ////发送数据
            //serialPort1.Write("P");

            //positionId = System.Text.Encoding.GetEncoding("utf-8").GetBytes(""+comboBox3.SelectedValue);
            //steelyardNo = System.Text.Encoding.GetEncoding("utf-8").GetBytes(""+comboBox1.SelectedValue);
        }

        //计价秤回收 信息
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string sql = "";

            try
            {
                CheckForIllegalCrossThreadCalls = false;
                serialPort1.Encoding = Encoding.BigEndianUnicode;
                int leng = 0;
                leng = serialPort1.BytesToRead;
                byte[] readBuffer = new byte[leng];
                serialPort1.Read(readBuffer, 0, readBuffer.Length);
                string hexStr = ByteToString(readBuffer, readBuffer.Length);
                string weight = HexStringToASCII(hexStr);

                string pattern = @"(\d+)\.(\d+)";//匹配模式

                Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);

                MatchCollection matches = regex.Matches(weight);

                foreach (Match match in matches)
                {
                    weight = match.Value.Trim();
                }

                //serialPort1.Close();

                //查询数据是否存在
                sql = "select * from realTimeData where positionId = '{0}' and steelyardId = '{1}'";
                sql = string.Format(sql, Convert.ToString(comboBox3.SelectedValue), Convert.ToString(comboBox1.SelectedValue));

                MysqlUtil db = new MysqlUtil();
                DataSet ds = db.GetDataSet(sql);

                //将重量信息更新到数据库中
                if (ds.Tables[0].Rows.Count > 0)
                {
                    //更新重量信息
                    sql = "update realTimeData set weight ='{0}',update_by='{1}',update_time='{2}' where positionId='{3}' and steelyardId='{4}'";//数据已存在，更新sql
                    sql = string.Format(sql, weight, userInfo.Person_ID, DateTime.Now.ToString(), Convert.ToString(comboBox3.SelectedValue), Convert.ToString(comboBox1.SelectedValue));
                }
                else
                {
                    sql = "insert into realTimeData(positionId,steelyardId,weight,create_time,create_by) values ('{0}','{1}','{2}','{3}','{4}')";//数据不存在，新建sql
                    sql = string.Format(sql, Convert.ToString(comboBox3.SelectedValue), Convert.ToString(comboBox1.SelectedValue), weight, DateTime.Now.ToString(), userInfo.Person_ID);
                }

                MysqlUtil db2 = new MysqlUtil();
                db2.ExecuteSql(sql);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "提示信息");
            }

        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            String sql = "select * from steelyard_info where positionId = '{0}'";//在这儿写sql语句 
            sql = string.Format(sql, comboBox3.SelectedValue);
            MysqlUtil db = new MysqlUtil();
            DataSet ds = db.GetDataSet(sql);
            DataTable dt = ds.Tables[0];

            this.comboBox1.DataSource = dt;
            this.comboBox1.DisplayMember = "steelyardNo";
            this.comboBox1.ValueMember = "ID";
            //this.comboBox1.SelectedValue = "ID";

            comboBox1.SelectedIndex = -1;
        }

        private void Timer_TimesUp(object sender, System.Timers.ElapsedEventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            //到达指定时间5秒触发该事件
            serialPort1.Close();
            serialPort1.PortName = this.comboBox2.Text.ToString();
            serialPort1.BaudRate = int.Parse("9600");
            serialPort1.DataBits = int.Parse("8");
            serialPort1.Parity = Parity.None;
            serialPort1.StopBits = StopBits.One;

            serialPort1.Open();
            //发送数据
            serialPort1.Write("P");
        }

        /// <summary>
        /// 将一条十六进制字符串转换为ASCII
        /// </summary>
        /// <param name="hexstring">一条十六进制字符串</param>
        /// <returns>返回一条ASCII码</returns>
        public static string HexStringToASCII(string hexstring)
        {
            byte[] bt = HexStringToBinary(hexstring);
            string lin = "";
            for (int i = 0; i < bt.Length; i++)
            {
                lin = lin + bt[i] + " ";
            }


            string[] ss = lin.Trim().Split(new char[] { ' ' });
            char[] c = new char[ss.Length];
            int a;
            for (int i = 0; i < c.Length; i++)
            {
                a = Convert.ToInt32(ss[i]);
                c[i] = Convert.ToChar(a);
            }

            string b = new string(c);
            return b;
        }

        /**/
        /// <summary>
        /// 16进制字符串转换为二进制数组
        /// </summary>
        /// <param name="hexstring">字符串每个字节之间都应该有空格，大多数的串口通讯资料上面的16进制都是字节之间都是用空格来分割的。</param>
        /// <returns>返回一个二进制字符串</returns>
        public static byte[] HexStringToBinary(string hexstring)
        {

            string[] tmpary = hexstring.Trim().Split(' ');
            byte[] buff = new byte[tmpary.Length];
            for (int i = 0; i < buff.Length; i++)
            {
                buff[i] = Convert.ToByte(tmpary[i], 16);
            }
            return buff;
        }

        //字节数组转16进制字符串
        public string ByteToString(byte[] InBytes, int len)
        {
            string StringOut = "";
            for (int i = 0; i < len; i++)
            {
                StringOut = StringOut + String.Format("{0:X2} ", InBytes[i]);
            }
            return StringOut;
        }

        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            System.Environment.Exit(0);
        }
    }
}
